/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.dashboard.datasource;

import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 表分片策略
 *
 * @auther ebert_chan
 */
public class TableShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    private static final String SHARDING_COLUMN_NAME = "member_id";

    /*
     * @see org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm#doSharding(java.util.Collection,
     * org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue)
     */
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<Long> shardingValue) {
        List<String> targetNames = new ArrayList<>();
        Map<String, Collection<Long>> valueMap = shardingValue.getColumnNameAndShardingValuesMap();
        Collection<?> values = valueMap.get(SHARDING_COLUMN_NAME);
        for (Object memberId : values) {
            String suffix = getSuffix((memberId instanceof Long) ? (Long) memberId : Long.valueOf(memberId.toString()));
            for (String name : availableTargetNames) {
                if (name.endsWith(suffix)) {
                    targetNames.add(name);
                }
            }
        }

        return targetNames;
    }

    private String getSuffix(Long memberId) {

        String n = String.valueOf(memberId % 256);
        for (int i = n.length(); i < 3; i++) {
            n = "0" + n;
        }
        return n;
    }

}
